import * as THREE from 'three';
import { Vec3 } from '@/core/types';
import { HostileEntity } from './HostileEntity';
import { EntityType, EntityStats, AIState } from './types';
import { WorldManager } from '@/world/WorldManager';
import { ItemDropManager } from '@/world/ItemDrop';
import { BlockType } from '@/blocks/types';

export class Enderman extends HostileEntity {
  private teleportCooldown = 0;
  private teleportInterval = 3.0; // 3秒瞬移间隔
  private waterDamageTimer = 0;
  private isInWater = false;
  private aggroRange = 64; // 末影人的仇恨范围很大

  constructor(id: string, position: Vec3, worldManager: WorldManager, itemDropManager?: ItemDropManager) {
    const stats: EntityStats = {
      maxHealth: 40,
      moveSpeed: 1.8,
      jumpHeight: 1.0,
      attackDamage: 7,
      attackRange: 2,
      detectionRange: 64,
      size: { width: 0.6, height: 2.9 } // 末影人很高
    };

    super(id, EntityType.ENDERMAN, position, worldManager, stats, itemDropManager);
  }

  protected createMesh(): void {
    // 创建末影人模型（黑色，细长）
    const group = new THREE.Group();

    // 身体（很长很细）
    const bodyGeometry = new THREE.BoxGeometry(0.6, 1.8, 0.3);
    const bodyMaterial = new THREE.MeshLambertMaterial({ color: 0x000000 }); // 纯黑色
    const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
    body.position.set(0, 1.4, 0);
    group.add(body);

    // 头部（方形，黑色）
    const headGeometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
    const headMaterial = new THREE.MeshLambertMaterial({ color: 0x000000 });
    const head = new THREE.Mesh(headGeometry, headMaterial);
    head.position.set(0, 2.6, 0);
    group.add(head);

    // 紫色发光的眼睛
    const eyeGeometry = new THREE.BoxGeometry(0.08, 0.08, 0.1);
    const eyeMaterial = new THREE.MeshBasicMaterial({ 
      color: 0xFF00FF // 紫色
    });
    
    const leftEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
    leftEye.position.set(-0.1, 2.65, -0.24);
    group.add(leftEye);
    
    const rightEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
    rightEye.position.set(0.1, 2.65, -0.24);
    group.add(rightEye);

    // 长臂
    const armGeometry = new THREE.BoxGeometry(0.2, 1.2, 0.2);
    const armMaterial = new THREE.MeshLambertMaterial({ color: 0x000000 });
    
    const leftArm = new THREE.Mesh(armGeometry, armMaterial);
    leftArm.position.set(-0.5, 1.4, 0);
    group.add(leftArm);
    
    const rightArm = new THREE.Mesh(armGeometry, armMaterial);
    rightArm.position.set(0.5, 1.4, 0);
    group.add(rightArm);

    // 长腿
    const legGeometry = new THREE.BoxGeometry(0.2, 1.2, 0.2);
    const legMaterial = new THREE.MeshLambertMaterial({ color: 0x000000 });
    
    const leftLeg = new THREE.Mesh(legGeometry, legMaterial);
    leftLeg.position.set(-0.15, 0.6, 0);
    group.add(leftLeg);
    
    const rightLeg = new THREE.Mesh(legGeometry, legMaterial);
    rightLeg.position.set(0.15, 0.6, 0);
    group.add(rightLeg);

    // 设置阴影
    group.traverse((child) => {
      if (child instanceof THREE.Mesh) {
        child.castShadow = true;
        child.receiveShadow = true;
      }
    });

    this.mesh = group;
  }

  protected onAttack(): void {
    console.log(`Enderman ${this.id} attacks with teleportation!`);
    
    // 末影人攻击时可能会瞬移
    if (Math.random() < 0.3) { // 30%概率瞬移
      this.teleport();
    }
  }

  public update(deltaTime: number): void {
    super.update(deltaTime);
    
    // 更新瞬移冷却
    if (this.teleportCooldown > 0) {
      this.teleportCooldown -= deltaTime;
    }
    
    // 检查是否在水中
    this.checkWaterContact();
    
    // 如果在水中，受到伤害
    if (this.isInWater) {
      this.waterDamageTimer += deltaTime;
      if (this.waterDamageTimer >= 0.5) { // 每0.5秒受到伤害
        this.takeDamage(2);
        this.waterDamageTimer = 0;
        console.log(`Enderman ${this.id} takes water damage!`);
        
        // 尝试瞬移逃离水
        this.teleport();
      }
    }
    
    // 末影人特有的行为
    this.addEndermanBehavior(deltaTime);
  }

  private checkWaterContact(): void {
    // 检查末影人是否接触到水或含水树叶
    const checkPositions = [
      this.position,
      { x: this.position.x, y: this.position.y + 1, z: this.position.z },
      { x: this.position.x, y: this.position.y + 2, z: this.position.z }
    ];

    this.isInWater = false;
    for (const pos of checkPositions) {
      const blockType = this.worldManager.getBlock(pos);
      if (blockType === BlockType.WATER || blockType === BlockType.WET_LEAVES) {
        this.isInWater = true;
        break;
      }
    }
  }

  private teleport(): boolean {
    if (this.teleportCooldown > 0) {
      return false;
    }

    // 尝试找到一个安全的瞬移位置
    for (let attempts = 0; attempts < 16; attempts++) {
      const teleportPos = {
        x: this.position.x + (Math.random() - 0.5) * 32,
        y: this.position.y + (Math.random() - 0.5) * 16,
        z: this.position.z + (Math.random() - 0.5) * 32
      };

      // 确保Y坐标在合理范围内
      teleportPos.y = Math.max(1, Math.min(60, teleportPos.y));

      if (this.canTeleportTo(teleportPos)) {
        // 瞬移效果
        this.createTeleportEffect(this.position);
        
        // 更新位置
        this.position = teleportPos;
        
        // 瞬移效果
        this.createTeleportEffect(this.position);
        
        // 设置冷却时间
        this.teleportCooldown = this.teleportInterval;
        
        console.log(`Enderman ${this.id} teleported to (${teleportPos.x.toFixed(1)}, ${teleportPos.y.toFixed(1)}, ${teleportPos.z.toFixed(1)})`);
        return true;
      }
    }

    return false;
  }

  private canTeleportTo(position: Vec3): boolean {
    // 检查瞬移位置是否安全
    const halfWidth = this.stats.size.width / 2;
    const height = this.stats.size.height;

    // 检查是否有足够的空间
    for (let y = 0; y < Math.ceil(height); y++) {
      const checkPos = { x: position.x, y: position.y + y, z: position.z };
      const blockType = this.worldManager.getBlock(checkPos);
      
      // 不能瞬移到固体方块中
      if (blockType > 0 && blockType !== BlockType.AIR) {
        return false;
      }
      
      // 不能瞬移到水中
      if (blockType === BlockType.WATER || blockType === BlockType.WET_LEAVES) {
        return false;
      }
    }

    // 检查脚下是否有支撑
    const groundPos = { x: position.x, y: position.y - 1, z: position.z };
    const groundBlock = this.worldManager.getBlock(groundPos);
    return groundBlock > 0 && groundBlock !== BlockType.AIR;
  }

  private createTeleportEffect(position: Vec3): void {
    // 创建紫色粒子效果（简化版）
    if (this.mesh && this.mesh.parent) {
      const particleCount = 20;
      for (let i = 0; i < particleCount; i++) {
        const particle = new THREE.Mesh(
          new THREE.SphereGeometry(0.05),
          new THREE.MeshBasicMaterial({ 
            color: 0xFF00FF,
            transparent: true,
            opacity: 0.8
          })
        );
        
        particle.position.set(
          position.x + (Math.random() - 0.5) * 2,
          position.y + Math.random() * 3,
          position.z + (Math.random() - 0.5) * 2
        );
        
        this.mesh.parent.add(particle);
        
        // 粒子动画
        const startTime = Date.now();
        const animate = () => {
          const elapsed = Date.now() - startTime;
          if (elapsed > 1000) {
            if (particle.parent) {
              particle.parent.remove(particle);
            }
            return;
          }
          
          particle.position.y += 0.02;
          particle.material.opacity = 0.8 * (1 - elapsed / 1000);
          requestAnimationFrame(animate);
        };
        animate();
      }
    }
  }

  private addEndermanBehavior(deltaTime: number): void {
    // 末影人在受到攻击时会瞬移
    if (this.ai?.state === 'attacking' && Math.random() < 0.01) {
      this.teleport();
    }

    // 末影人会发出奇怪的声音
    if (Math.random() < 0.001) {
      console.log(`Enderman ${this.id}: *eerie sound*`);
    }

    // 末影人在白天会寻找阴影
    // 这里简化处理，随机移动
    if (this.ai?.state === 'idle' && Math.random() < 0.005) {
      this.teleport();
    }
  }

  protected dropLoot(): void {
    // 末影人死亡时掉落末影珍珠
    console.log(`Enderman ${this.id} dropped an Ender Pearl!`);
    
    if (this.itemDropManager) {
      // 掉落末影珍珠
      this.itemDropManager.dropItem(BlockType.ENDER_PEARL, 1, this.position);
      
      // 小概率掉落额外的末影珍珠
      if (Math.random() < 0.25) { // 25%概率
        console.log(`Enderman ${this.id} dropped an extra Ender Pearl!`);
        this.itemDropManager.dropItem(BlockType.ENDER_PEARL, 1, this.position);
      }
    }
  }

  // 重写受伤逻辑，末影人受伤时会瞬移
  protected onDamage(amount: number): void {
    super.onDamage(amount);
    
    // 受伤时有很高概率瞬移
    if (Math.random() < 0.8) { // 80%概率瞬移
      this.teleport();
    }
  }

  // 末影人可以被玩家直视激怒
  public onPlayerLookAt(): void {
    if (this.ai && this.ai.state === 'idle') {
      this.ai.state = AIState.FOLLOWING;
      this.ai.stateTimer = 0;
      console.log(`Enderman ${this.id} has been provoked by player's stare!`);
    }
  }
}